#!/usr/bin/python

##
## Copyright (C) 2009 Luciano Xumerle <luciano.xumerle@gmail.com>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## 
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

import sys
import re

try:
    import pysqlite2.dbapi2 as sqlite
except:
    import sqlite3 as sqlite

def main():
   """main routine"""

   errorMsg="SYNTAX: " + sys.argv[0] + " <snp.txt> <snp.sqlite>\n"

   if len(sys.argv)!=3:
       print >>sys.stderr, errorMsg
       return

   # check parameters
   snpfile=sys.argv[1]
   database=sys.argv[2]

   if database=='' or snpfile=='':
           print >>sys.stderr, errorMsg
           return

   # create database connection
   sql=sqlite.connect(database)
   sql.execute("""PRAGMA CACHE_SIZE = 5000000""")
   cur = sql.cursor()

   # create database table
   query = """CREATE TABLE snp (chromosome text, sstop integer,
              rs text, direction text, bases text );"""
   cur.execute( query )

   # import data from txt file
   query = """INSERT INTO snp VALUES (?, ?, ?, ?, ?);"""
   count=0
   fout = open(snpfile, "a")
   for line in open(snpfile, "r"):
       row=re.split('\t', line.strip())
       cur.execute( query, (row[1], row[3], row[4], row[6], row[9]) )
       count+=1
       if count > 10000:
           sql.commit()
           count=0

   sql.commit()
   cur.execute("""CREATE INDEX idx ON snp(chromosome,sstop);""")

if __name__=='__main__': main()

